<template>
  <div class="content-table">
    <el-card>
      <div>
        <div class="list-h">
          <div>
            <el-button type="primary" @click="handleOpen" class="add-option"
              >添加</el-button
            >
          </div>
          <el-form
            :inline="true"
            class="demo-form-inline"
            :model="formInline"
            ref="formRef"
            @submit.prevent
          >
            <el-form-item label="科创对接人员" prop="nameLike">
              <el-input
                v-model.trim="formInline.nameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>

            <el-form-item label="所属单位" prop="deptNameLike">
              <el-input
                v-model.trim="formInline.deptNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>

            <el-form-item label="登记时间" prop="updateTime">
              <el-date-picker
                style="width: 90%"
                v-model.trim="formInline.updateTime"
                type="date"
              />
            </el-form-item>

            <el-form-item>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
          <el-table
            :data="state.tableData"
            border
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <el-table-column type="index" label="序号" width="60">
              <template v-slot="scope">
                <span>{{
                  (formInline.pageNum - 1) * formInline.pageSize +
                  scope.$index +
                  1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="科创对接人员"></el-table-column>

            <el-table-column
              prop="deptName"
              label="所属单位"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="createUserName"
              label="创建人"
            ></el-table-column>
            <el-table-column prop="lastUpdateTime" label="登记时间">
              <template v-slot="scope">
                {{
                  scope.row.lastUpdateTime
                    ? scope.row.lastUpdateTime.split(" ")[0]
                    : ""
                }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button type="text" @click="handleCheckDetail(row)">
                  查看
                </el-button>
                <el-button type="text" @click="handleEdit(row, true)">
                  编辑
                </el-button>
                <el-popconfirm
                  v-if="isAdmin"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDelete(row)"
                >
                  <template #reference>
                    <el-button
                      :disabled="row.isEmp === '1'"
                      type="text"
                      v-auth="`/expert/science--delete`"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>
      <re-pagination
        :total="total"
        v-show="total > 0"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
    <el-dialog
      title="科创对接人员"
      v-model="dialogFormVisible"
      destroy-on-close
      width="700px"
    >
      <el-form
        :model="state.detailInfo"
        ref="userFormRef"
        @submit.prevent
        :rules="formRules"
        label-width="130px"
        :validate-on-rule-change="false"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="userObj">
              <el-select
                v-model="state.detailInfo.userObj"
                style="width: 100%"
                filterable
                clearable
                remote
                placeholder="请输入姓名搜索"
                :remote-method="querySearchAsync"
                value-key="id"
                @change="handleSelect"
                @visible-change="handleVisible"
              >
                <el-option
                  id="default-option"
                  v-for="item in state.userList"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                ></el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="state.detailInfo.username"
                class="width-custom"
                disabled
                clearable
                placeholder="选择姓名后自动带出"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                disabled
                v-model.trim="state.detailInfo.email"
                class="width-custom"
                placeholder="选择姓名后自动带出"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phoneNum">
              <el-input
                disabled
                v-model.trim="state.detailInfo.phoneNum"
                class="width-custom"
                placeholder="选择姓名后自动带出"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属单位部门" prop="deptName">
              <el-input
                disabled
                v-model.trim="state.detailInfo.deptName"
                class="width-custom"
                placeholder="选择姓名后自动带出"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入内容"
                v-model="state.detailInfo.remark"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="end">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </el-row>
      </el-form>
    </el-dialog>

    <el-dialog
      v-model="detailVisible"
      destroy-on-close
      title="登记历史记录"
      width="80%"
    >
      <check-detail :abutmentId="abutmentId" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { cloneDeep } from "lodash-es";
import moment from "moment";
import { nextTick, onMounted, reactive, ref } from "vue";
import { ModeType } from "../science/types";
import CheckDetail from "./checkDetail.vue";
import {
  addAbutment,
  delAbutment,
  getAbutmentDetail,
  getAbutmentList,
  updateAbutmentDetail
} from "/@/api/expert";
import { getUsersForScience } from "/@/api/user";
import NotifMessage from "/@/utils/message/notification";
import { storageLocal } from "/@/utils/storage";
const formRef = ref<HTMLFormElement | null>(null) as any;
const userFormRef = ref<HTMLFormElement | null>(null) as any;

let loading = ref<boolean>(false);
let mode = ref<ModeType>("add");
let dialogFormVisible = ref<boolean>(false);
let detailVisible = ref<boolean>(false); // 查看详情弹窗状态
let abutmentId = ref<any>(0); // 查看详情ID
let total = ref<number>(0);
let formInline = reactive<any>({
  nameLike: "",
  deptNameLike: "",
  updateTime: "",
  pageNum: 1,
  pageSize: 10
});

let state: any = reactive({
  userList: [],
  tableData: [],
  detailInfo: {}
});
const formRules = {
  userObj: [
    { required: true, message: "请选中科创对接人员", trigger: "change" }
  ],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  phoneNum: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  deptName: [{ required: true, message: "请输入所属单位部门", trigger: "blur" }]
};

// 查看详情弹窗状态
const handleCheckDetail = async row => {
  detailVisible.value = true;
  abutmentId.value = row.id;
};

const handleSubmit = () => {
  userFormRef.value.validate(async (valid: any) => {
    if (valid) {
      if (mode.value === "add") {
        const { code, message } = await addAbutment(state.detailInfo);
        if (code === 200) {
          dialogFormVisible.value = false;
          getTableData();
        } else {
          dialogFormVisible.value = false;
          NotifMessage.error(message);
        }
      } else {
        delete state.detailInfo.pageInfo;
        const { code, message } = await updateAbutmentDetail(state.detailInfo);
        if (code === 200) {
          dialogFormVisible.value = false;
          getTableData();
        } else {
          dialogFormVisible.value = false;
          NotifMessage.error(message);
        }
      }
    }
    return false;
  });
};
const querySearchAsync = async (queryString: string) => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      name: queryString
    };
    const { code, data } = await getUsersForScience(params);
    if (code === 200) {
      state.userList = data.list.map(item => {
        return {
          id: item.id,
          name: item.deptName ? `${item.name}(${item.deptName})` : item.name,
          deptCode: item.deptCode,
          phoneNum: item.phoneNum,
          email: item.email,
          companyName: item.deptName,
          username: item.userName
        };
      });
      storageLocal.setItem("userList", state.userList);
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSelect = item => {
  state.detailInfo.email = item.email;
  if (item.name && item.name.indexOf("(") > -1) {
    const index = item.name.indexOf("(");
    state.detailInfo.name = item.name.slice(0, index);
  } else {
    state.detailInfo.name = item.name;
  }
  state.detailInfo.userObj.name = state.detailInfo.name;
  state.detailInfo.phoneNum = item.phoneNum;
  state.detailInfo.deptName = item.companyName;
  state.detailInfo.userId = item.id;
  state.detailInfo.username = item.username;
  formRef.value.clearValidate();
};

const handleVisible = isVisible => {
  if (isVisible) {
    let userList = storageLocal.getItem("userList");
    state.userList = [...userList];
  }
};

// 请求表格数据
async function getTableData(obj: object = {}) {
  // 真实请求待添加
  loading.value = true;
  try {
    const { code, data } = await getAbutmentList(obj);
    if (code === 200) {
      state.tableData = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}

// 打开添加人员弹窗
const handleOpen = (): void => {
  state.detailInfo = {};
  dialogFormVisible.value = true;
  mode.value = "add";
  nextTick(() => {
    userFormRef.value.resetFields();
  });
};

// 重置条件
const handleReset = (): void => {
  formRef.value.resetFields();
  handleSearch();
};

// 根据条件进行搜索
const handleSearch = (): void => {
  const params = cloneDeep(formInline);
  if (formInline.updateTime) {
    params.updateTime = moment(formInline.updateTime).format("YYYY-MM-DD");
  } else {
    params.updateTime = "";
  }
  getTableData(params);
};

// 编辑用户
const handleEdit = async (row): void => {
  querySearchAsync(row.name);
  try {
    const { code, data } = await getAbutmentDetail({ id: row.id });
    if (code === 200) {
      dialogFormVisible.value = true;
      mode.value = "edit";
      state.detailInfo = data;
      abutmentId.value = row.id;
      state.detailInfo.username = data.username;
      state.detailInfo.userObj = { id: row.userId, name: row.name };
    }
  } catch (err) {
    console.log(err);
  }
};

// 删除用户
const handleDelete = async (item: any) => {
  try {
    const { code, message } = await delAbutment({ id: item.id });
    if (code === 200) {
      // successMessage(`${message}`);
      NotifMessage.success(message);
      getTableData(formInline);
    } else {
      // warnMessage(`${message}`);
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};
// 请求数据
getTableData(formInline);
querySearchAsync("");

// 是否是管理员
const isAdmin = ref(false);
onMounted(() => {
  const userInfo = storageLocal.getItem("rdms-info");
  isAdmin.value = userInfo.roleId == 1;
});
</script>
<style>
.el-popper {
  max-width: 500px;
  line-height: 1.5;
}
</style>
<style lang="scss" scoped></style>
